<?php
/**
 * GZ Class
 * 
 * @author	zhangjian<smile_for_life@sina.cn>
 * @date	2014-01-14
 */
 class GZ
 {
	protected $_fd = null;
	
	/**
	 * construct instance
	 * @param string $gz_file file of format is gz
	 * @param string $mode rb or wb reference gzopen
	 */ 
	public function __construct($gz_file = '')
	{
		if(is_file($gz_file)){
			$this->open($gz_file);
		}
	}
	
	public function __destruct()
	{
		if(!is_null($this->_fd)){
			$this->close();
		}
		
	}
	
	/**
	 * get line can filter by callback
	 * @param callback function name or array of class and method
	 * @return string
	 */
	public function read($callback = null, $all = false)
	{
		$return = false;
		$result = array();
		
		if($this->_fd){
			do{
				$return = gzgets($this->_fd);
				
				if(is_callable($callback)){
					$result[] = call_user_func($callback,$return);
				}
			}while(!gzeof($this->_fd) && $all);
			
			$return = $result;
		}
		
		return $return;
		
	}
	
	public function write($string, $callback = null, $all = false)
	{
		$return = false;
		if($this->_fd){
			do{
			if(is_callable($callback)){
				$string = call_user_func($callback,$string);
			}
			$return = gzwrite($this->_fd, $string);
			}while(!gzeof($this->_fd) && $all);
		}
		
		return $return;
	
	}
	
	public function open($gz_file = '', $mode = 'rb')
	{
		if(is_file($gz_file)){
			$this->_fd = gzopen($gz_file,$mode);
		}
	}
	
	public function close()
	{
		if($this->_fd){
			gzclose($this->_fd);
		}
	}
	
 }